package online.sh.cn.fy.users.servlet;

import java.io.IOException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import online.sh.cn.fy.common.api.SqlUtil;
import online.sh.cn.fy.common.utils.CompareState;
import online.sh.cn.fy.common.utils.CookieUtil;
import online.sh.cn.fy.common.utils.DES3Util;
import online.sh.cn.fy.common.utils.ResponseUtils;
import online.sh.cn.fy.common.utils.TokenUtils;
import online.sh.cn.fy.common.utils.WxUtils;
import online.sh.cn.fy.users.utils.PointsUtil;

/**
 * 验证是否认证用户
 * 自动签到
 */
@WebServlet("/loginOpen")
public class UserCheckLogin extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String openid=CookieUtil.getCookieValueByName(request, "openid");
		JSONObject json=new JSONObject();
		if(null!=openid && ""!=openid){
			String uuid=CookieUtil.getCookieValueByName(request, "uuid");
			if(null!=uuid && uuid.equals("0")){
				try {
					openid=DES3Util.decrypt(openid);
				} catch (Exception e) {
					log(e.getMessage());
				}
				TokenUtils to=new TokenUtils();
				WxUtils wxu=new WxUtils();
				String accesstoken=to.getAccesstoken();
				JSONObject jsonuser=JSONObject.fromObject(wxu.getUserinfo(accesstoken, openid));
				if(jsonuser.containsKey("errcode")){
					System.out.println("******AccessToken失效,重新获取******");
					JSONObject jsontoken=JSONObject.fromObject(wxu.getAccessToken());
					//更新数据库accesstoken
					to.updateAccessToken(jsontoken.get("access_token").toString());
					accesstoken=jsontoken.get("access_token").toString();
					JSONObject jsonuseragain=JSONObject.fromObject(wxu.getUserinfo(accesstoken, openid));
					String nickname=(String)jsonuseragain.get("nickname");
					String headimg=(String)jsonuseragain.get("headimgurl");
					int subscribetime=(int)jsonuseragain.get("subscribe_time");
					nickname=nickname.replaceAll("[\\x{10000}-\\x{10FFFF}]", "");
					to.UpdateNicknameHeadimg(nickname, headimg, openid,changeTime(String.valueOf(subscribetime)));
					json.put("nickname", nickname);
					json.put("headimg", headimg);	
				}else{
					String nickname=(String)jsonuser.get("nickname");
					String headimg=(String)jsonuser.get("headimgurl");
					int subscribetime=(int)jsonuser.get("subscribe_time");
					nickname=nickname.replaceAll("[\\x{10000}-\\x{10FFFF}]", "");
					to.UpdateNicknameHeadimg(nickname, headimg, openid,changeTime(String.valueOf(subscribetime)));
					json.put("nickname", nickname);
					json.put("headimg", headimg);
				}
				Map user=to.getFyUserinfoMap(openid);
				String school=to.getSchoolBand(user.get("school").toString());
				if(null!=school && ""!=school){
					json.put("school", 0);       //代表绑定学校为认证学校
				}else{
					json.put("school", 1);       //非认证学校，需重新绑定
				}
				int today_points;
				String level=(String) user.get("level");
				int ex=(int) user.get("experience");
				int points=(int) user.get("points");
				Calendar cal=Calendar.getInstance();
				int year=cal.get(Calendar.YEAR);
				int month=cal.get(Calendar.MONTH)+1;
				String day=String.valueOf(cal.get(Calendar.DATE));
				SqlUtil tu=new SqlUtil();
				if (tu.checkUser(openid, year, month)) {	//代表非首次签到用户
					Map signuser=tu.checkUserSignUp(openid, year, month);
					int today=(int)signuser.get("sign_today");
					String inrow=(String)signuser.get("sign_setday")+","+day;
					if(today==0){
						tu.updateUserSignUp(openid, inrow, year, month);
						String[] set=inrow.split(",");
						String sign_state=CompareState.getMaxState(set);
						String sign_six=String.valueOf(signuser.get("sign_six"));     //当月连续签到6天标识，0未领取，1已领取
						if(set.length<5){
							today_points=getRandom(2,99);      	//前5次签到
						}else{
							if(set.length<12){
								today_points=getRandom(11,29);  //前5次后7次签到
							}else{
								today_points=getRandom(1,9);	//剩余18次签到
							}
						}
						today_points=PointsUtil.PlusPoints(today_points, ex);
						tu.updateUserSignUpState(openid, Integer.parseInt(sign_state),today_points,today_points, year, month,0);
						to.savePointsEvent(openid, "", "每日签到", "+"+today_points);
						if(sign_six.equals("0") && sign_state.equals("6")){
							tu.updateUserSignUpState(openid, Integer.parseInt(sign_state),today_points, 100, year, month ,1);
							to.savePointsEvent(openid, "", "连续6天签到", "+100");
							level=PointsUtil.CompareLevel(ex+today_points+100);
							tu.updateUserExperience(openid, today_points+100, today_points+100, level);
							json.put("six", 1);
						}else{
							level=PointsUtil.CompareLevel(ex+today_points);
							tu.updateUserExperience(openid, today_points, today_points, level);
							json.put("six", 0);
						}
						json.put("points", points+today_points);
						json.put("level", level);
						json.put("today", 0);
					}else{
						today_points=(int) signuser.get("today_points");
						json.put("points", points);
						json.put("level", level);
						json.put("today", 1);
						json.put("six", 0);
					}
				}else{
					String elseday="";
					if (cal.get(Calendar.DATE)>1) {
						for (int i = 1; i <cal.get(Calendar.DATE); i++) {
							elseday=elseday+String.valueOf(i)+",";
						}
						elseday=elseday.substring( 0, elseday.length() -1);
					}
					today_points=getRandom(2, 99);
					today_points=PointsUtil.PlusPoints(today_points, ex);
					tu.insertSignUser(openid, 1, 1, 1, today_points, today_points, 0, month, year, day, elseday);
					to.savePointsEvent(openid, "", "每日签到", "+"+today_points);
					level=PointsUtil.CompareLevel(ex+today_points);
					tu.updateUserExperience(openid, today_points, today_points, level);
					json.put("points", points+today_points);
					json.put("level", level);
					json.put("today", 0);
					json.put("six", 0);
				}
				json.put("todaypoints", today_points);
				json.put("user", user);
				json.put("result", 1);
				ResponseUtils.renderJson(response, json.toString());
			}else{
				json.put("result", 2);
				ResponseUtils.renderJson(response, json.toString());
			}
		}else{
			json.put("result", 0);
			ResponseUtils.renderJson(response, json.toString());
		}
	}
	
	//返回指定范围随机数
	public static int getRandom(int min, int max){
	    SecureRandom random = new SecureRandom();
	    int s = random.nextInt(max) % (max - min + 1) + min;
	    return s;
	}
	
	public static String changeTime(String time){
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		long ntime=new Long(time);  
		String d = format.format(ntime*1000);
		return d;
	}

//	public static void main(String[] args) {
//		 System.out.println(getRandom(1,9));
//		 SecureRandom random = new SecureRandom();
//		 random
//	}

}
